package com.edu.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.alibaba.fastjson.JSON;
import com.edu.entiy.Book;
import com.edu.entiy.BookType;
import com.edu.entiy.History;
import com.edu.entiy.Page;
import com.edu.entiy.User;
import com.edu.service.BookService;
import com.edu.service.BookTypeService;
import com.edu.service.HistoryService;
import com.edu.service.UserService;
import com.edu.service.impl.BookServiceImpl;
import com.edu.service.impl.BookTypeServiceImpl;
import com.edu.service.impl.HistoryServiceImpl;
import com.edu.service.impl.UserServiceImpl;
import com.edu.utils.PageTool;
import com.edu.utils.PaginationUtils;
import com.edu.utils.ResBean;

@WebServlet("/bookServlet/*")
public class BookServlet extends BaseServlet{
	private BookService bookService = new BookServiceImpl();
	private BookTypeService bookTypeService = new BookTypeServiceImpl();
	private UserService userService = new UserServiceImpl();
	private HistoryService historyService = new HistoryServiceImpl();
	public void selectByPage(HttpServletRequest request, HttpServletResponse response) {
		//获取传入的数据
       String _currentPage = request.getParameter("currentPage");
       String _pageSize = request.getParameter("pageSize");
       int currentPage = Integer.parseInt(_currentPage);
       int pageSize = Integer.parseInt(_pageSize);
       Page<Book> page = bookService.selectByPage(currentPage, pageSize);
       System.out.println(page);
	}
	//检查图书名称是否唯一
	public void checkBookName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String bookName = request.getParameter("bookName");
		Book book =  bookService.selectBookByName(bookName);
		ResBean resBean = new ResBean();
		if(book == null) {
			//该图书不存在
			resBean.setCode(200);
			resBean.setMessage("图书名称可以使用");
		}else {
			resBean.setCode(400);
			resBean.setMessage("图书名称不可以重复");
		}
		String json = JSON.toJSONString(resBean);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(json);
	}
	//分页
	public void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取用户数据
		HttpSession session =  request.getSession();
		User user = (User)session.getAttribute("user");
		//获取传入的数据
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        PageTool<Book> pageTool = bookService.page(_currentPage, _pageSize);
        String pageResult =  PaginationUtils.getPagation(pageTool.getTotalCount(), pageTool.getCurrentPage(), pageTool.getPageSize(), "/bookServlet/page");
        List<BookType> bookTypes =  bookTypeService.selectBookTypes();
        //存数据
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("bookList", pageTool.getRows());
        request.setAttribute("typeList", bookTypes);
        if(user.getStatus() == 2) {
        	request.getRequestDispatcher("/admin/admin_book.jsp").forward(request, response);
        }else {
        	request.getRequestDispatcher("/user/select.jsp").forward(request, response);
        }
        
	}
	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, ServletException, IOException {
		//获取传入的数据
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
        String word = request.getParameter("word");
        PageTool<Book> pageTool =  bookService.page(_currentPage, _pageSize, word);
        String pageResult = PaginationUtils.getPagation(pageTool.getTotalCount(), pageTool.getCurrentPage(), pageTool.getPageSize(), "/bookServlet/selectByPageAndCondition");
        request.setAttribute("bookList", pageTool.getRows());
        request.setAttribute("pageResult", pageResult);
        //获取用户身份
        HttpSession session =  request.getSession();
        User user = (User)session.getAttribute("user");
        if(user.getStatus() == 2) {
        	request.getRequestDispatcher("/admin/admin_book.jsp").forward(request, response);
        }else {
        	request.getRequestDispatcher("/user/select.jsp").forward(request, response);
        }
       
        
	}
	//添加书籍
	public void addBook(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, ServletException, IOException {
		//获取参数
		Book book = new Book();
		BeanUtils.populate(book, request.getParameterMap());
		int count = bookService.addBook(book);
		if(count == 1 ) {
			System.out.println("添加成功");
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
		}else if(count == -1){
			System.out.println("图书名称不可用!");
		}else {
			System.out.println("添加失败");
		}
	}
	
	
	/**
	 * 图书修改方法
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void updateBook(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, ServletException, IOException {
		Book book = new Book();
		BeanUtils.populate(book, request.getParameterMap());
		System.out.println(book);
		//对数据进行合法校验
		if(book.getBookNum()<0) {
			System.out.println("数据输入不合法!");
			return;
		}
		int count = bookService.updateBook(book);
		if(count == 1) {
			System.out.println("修改成功");
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
			
		}else {
			System.out.println("修改失败");
		}
	}
	/**
	 * 删除图书
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void deleteBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取参数
		String _bookId = request.getParameter("bookId");
		int bookId = Integer.parseInt(_bookId);
		//删除之前先查询该书是否仍在被借阅
		History history = historyService.selectByBookId(bookId);
		if(history == null ) {
			System.out.println("删除成功");
			bookService.deleteBook(bookId);
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
		}else {
			request.setAttribute("errorMes",1);
			System.out.println("删除失败");
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
			return;
		}
	}
	/**
	 * 图书借阅
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public void borrowBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取被借阅图书的id
		String _bookID = request.getParameter("bookId");
		int bookId = Integer.parseInt(_bookID);
		//获取当前用户的信息
		HttpSession session =  request.getSession();
		User user = (User)session.getAttribute("user");
		//判断当前用户的借书次数
		if(user.getLendMaxNum()<=0) {
			request.setAttribute("errorMessage",1);
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
			return;
		}
		//判断当前书籍的数量
		Book book =  bookService.selectBookById(bookId);
		if(book.getBookNum()<=0) {
			request.setAttribute("errorMessage",2);
			request.getRequestDispatcher("/bookServlet/page").forward(request, response);
			return;
		}else {
			//调用对应接口
			boolean result = bookService.borrowBook(user, bookId);
			if(result) {
				System.out.println("借阅成功");
				//借阅成功之后,我们要更新session中用户的信息
				User newUser =  userService.selectUserById(user.getId());
				session.setAttribute("user", newUser);
				request.getRequestDispatcher("/historyServlet/page").forward(request, response);;
			}
		}
		
	}
	
	public void OrderByTimesDesc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		//这里查出来的list肯定是降序排列的
		//获取用户身份
		HttpSession session = request.getSession();
		User user =(User) session.getAttribute("user");
		String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
		PageTool<Book> pageTool = bookService.selectBooksOrderByTimesDesc(_currentPage, _pageSize);
		String pageResult = PaginationUtils.getPagation(pageTool.getTotalCount(), pageTool.getCurrentPage(), pageTool.getPageSize(), "/bookServlet/OrderByTimesDesc");
		request.setAttribute("pageResult", pageResult);
		request.setAttribute("bookList", pageTool.getRows());
		System.out.println("转发的数据:"+pageTool.getRows());
		if(user.getStatus() == 2) {
			request.getRequestDispatcher("/admin/admin_bdtimes.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("/user/bdtimes.jsp").forward(request, response);
		}
	}	
			
	public void BestReading(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		//这里查出来的list肯定是降序排列的
		//获取用户身份
		HttpSession session = request.getSession();
		User user =(User) session.getAttribute("user");
		
		if(user.getStatus() == 2) {
			request.getRequestDispatcher("/admin/admin_brtimes.jsp").forward(request, response);
		}else {
			request.getRequestDispatcher("/user/brtimes.jsp").forward(request, response);
		}
	}	
}
